package com.note.rabbitMq.server;

import com.rabbitmq.client.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName QueueingConsumer
 * @Description TODO
 * @Author QiBin
 * @Date 2020/6/1115:07
 * @Version 1.0
 **/
@Component
public class QueueingConsumer extends DefaultConsumer {

    //该对象在4以后被废止    保留老代码不变   继承defaultConsumer
    private LinkedBlockingQueue<Delivery> queue;

    public QueueingConsumer(Channel channel) {
        super(channel);
        queue = new LinkedBlockingQueue<>();
    }

    public QueueingConsumer(Channel channel, int size) {
        super(channel);
        queue = new LinkedBlockingQueue<>(size);
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        Delivery delivery = new Delivery();
        delivery.setBody(body);
        delivery.setProperties(properties);
        delivery.setEnvelope(envelope);
        try {
            queue.put(delivery);
        } catch (InterruptedException e) {

        }
    }

    public Delivery nextDelivery() throws InterruptedException, ShutdownSignalException, ConsumerCancelledException {
        return queue.take();
    }

    public Delivery nextDelivery(long timeout) throws InterruptedException, ShutdownSignalException, ConsumerCancelledException {
        return queue.poll(timeout, TimeUnit.MILLISECONDS);
    }

    public class Delivery {
        private BasicProperties properties;
        private byte[] body;
        private Envelope envelope;

        public BasicProperties getProperties() {
            return properties;
        }

        public void setProperties(BasicProperties properties) {
            this.properties = properties;
        }

        public byte[] getBody() {
            return body;
        }

        public void setBody(byte[] body) {
            this.body = body;
        }

        public Envelope getEnvelope() {
            return envelope;
        }

        public void setEnvelope(Envelope envelope) {
            this.envelope = envelope;
        }

    }
}
